package com.donn.securitycontrolplatform.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dahuatech.icc.exception.ClientException;
import com.donn.securitycontrolplatform.common.Result;
import com.donn.securitycontrolplatform.db1.mapper.TUserMapper;
import com.donn.securitycontrolplatform.db1.mapper.TUserRoleMapper;
import com.donn.securitycontrolplatform.expection.BusinessException;
import com.donn.securitycontrolplatform.personinfo.entity.PersonInfo;
import com.donn.securitycontrolplatform.personinfo.service.IPersonInfoService;
import com.donn.securitycontrolplatform.role.entity.TRole;
import com.donn.securitycontrolplatform.role.service.ITRoleService;
import com.donn.securitycontrolplatform.user.entity.DaHuaPerson;
import com.donn.securitycontrolplatform.user.entity.TUser;
import com.donn.securitycontrolplatform.user.response.UserInfo;
import com.donn.securitycontrolplatform.user.service.ITUserService;
import com.donn.securitycontrolplatform.userwhitelist.entity.TUserWhiteList;
import com.donn.securitycontrolplatform.userwhitelist.service.ITUserWhiteListService;
import com.donn.securitycontrolplatform.utils.DaHuaUtil;
import com.donn.securitycontrolplatform.utils.FileUtil;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author zhenglixiang
 * @since 2022-06-10
 */
@Service
@Slf4j
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    @Autowired
    TUserMapper mapper;

    @Autowired
    TUserRoleMapper tUserRoleMapper;
    @Autowired
    DaHuaUtil daHuaUtil;
    @Autowired
    IPersonInfoService personInfoService;
    @Autowired
    ITUserWhiteListService userWhiteListService;


    /**
     * 根据personId添加人员到门禁
     */
    @Override
    public void authByPersonId(Long personId, Long quantumId) {
        daHuaUtil.authByPersonId(personId, quantumId);
    }


    @Override
    public Long synchronizeAdd(String name, String idno, String cardNumber) throws BusinessException, ClientException {

        log.info("开始同步大华摄像头...");
        //获取大华人员布控白名单库信息 如果没有则创建
        Long whiteListId = daHuaUtil.getWhiteListUserStore();
        PersonInfo personInfo = personInfoService.getPersonByNameAndIdNo(name, idno);
        log.info("persion=" + personInfo.toString());
        //生成头像图片的base64
        String imgBase64 = FileUtil.encryptToBase64(DaHuaUtil.USER_FACE_PATH + personInfo.getImgPath());

        //上传人像信息到大华系统
        String imgPath = daHuaUtil.addUserPhoto(personInfo.getImgPath(), imgBase64);

        //数据库中新增用户后 同步用户数据到大华人员布控
        Long personId = daHuaUtil.addUser(personInfo.getName(), personInfo.getSex(), "1", personInfo.getIdno(),
                whiteListId,
                daHuaUtil.generateBirthday(personInfo.getIdno()), imgPath);

        log.info("同步大华摄像头数据成功...");
        //保存用户白名单信息
        TUserWhiteList userWhiteList = new TUserWhiteList();
        userWhiteList.setUserId(personInfo.getId());
        userWhiteList.setGroupId(whiteListId);
        userWhiteList.setPersonId(personId);
        userWhiteList.setCreateTime(LocalDateTime.now());
        userWhiteList.setCardNumber(cardNumber);
        userWhiteListService.save(userWhiteList);
        return personId;

    }

    @Override
    public Result synchronizeDelete(Integer userId) throws BusinessException, ClientException {
        TUserWhiteList whiteList = userWhiteListService.getByUserId(userId);
        daHuaUtil.deleteUser(whiteList.getPersonId(), whiteList.getGroupId());
        return Result.success("");
    }

    @Override
    public Result synchronizeUpdate(DaHuaPerson person) throws BusinessException, ClientException {
        TUserWhiteList userWhiteList = userWhiteListService.getByUserId(person.getId());
        PersonInfo personInfo = personInfoService.getPersonByNameAndIdNo(person.getName(), person.getIdno());

        String birthday = daHuaUtil.generateBirthday(personInfo.getIdno());
        String imgPath = daHuaUtil.addUserPhoto(personInfo.getImgPath(), FileUtil.encryptToBase64(DaHuaUtil.USER_FACE_PATH + personInfo.getImgPath()));

        daHuaUtil.updateUser(userWhiteList.getPersonId(), person.getName(), person.getSex(), "1", person.getIdno(), userWhiteList.getGroupId(), birthday, imgPath);
        return Result.success("");
    }

    @Override
    public void deleteMj(Integer userId) throws BusinessException, ClientException {
        TUserWhiteList byUserId = userWhiteListService.getByUserId(userId);
        daHuaUtil.deleteMj(byUserId.getCardNumber());
    }

    @Override
    public Result update(TUser user) {
        try {
            user.setUpdateTime(LocalDateTime.now());
            return Result.success(mapper.updateById(user));
        } catch (Exception e) {
            log.error("update error", e);
            return Result.init(500, "service error", e.getMessage());
        }
    }

    @Autowired
    ITRoleService roleService;

    @Override
    public Result selectUserList(TUser user, Page page) {
        try {
            QueryWrapper<TUser> queryWrappe = new QueryWrapper<>();
            if (StringUtil.isNotEmpty(user.getUserName())) {
                queryWrappe.lambda().eq(TUser::getUserName, user.getUserName());
            }
            if (StringUtil.isNotEmpty(user.getIden())) {
                queryWrappe.lambda().eq(TUser::getIden, user.getIden());
            }
            if (user.getSex() != null) {
                queryWrappe.lambda().eq(TUser::getSex, user.getSex());
            }
            if (StringUtil.isNotEmpty(user.getCreateBy())) {
                queryWrappe.lambda().eq(TUser::getCreateBy, user.getCreateBy());
            }
            IPage<TUser> tUserIPage = page(page, queryWrappe);
            List<TUser> userList = tUserIPage.getRecords();
            List<UserInfo> userInfoList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(userList)) {
                UserInfo userInfo;
                for (TUser tUser : userList) {
                    userInfo = new UserInfo();
                    BeanUtils.copyProperties(tUser, userInfo);
                    TRole role = roleService.getRoleByUserId(tUser.getUserId());
                    if (role != null) {
                        userInfo.setIconType(role.getIconType());
                        userInfo.setIconUrl(role.getIconUrl());
                        userInfo.setRoleName(role.getRoleName());
                    }
                    userInfoList.add(userInfo);
                }
            }
            return Result.success(userInfoList);
        } catch (Exception e) {
            log.error("query error", e);
            return Result.init(500, "service error", e.getMessage());
        }
    }

    @Override
    public Result getUserById(Long userId) {
        try {
            UserInfo userInfo = null;
            TUser user = getById(userId);
            if (user != null) {
                userInfo = new UserInfo();
                BeanUtils.copyProperties(user, userInfo);
                TRole role = roleService.getRoleByUserId(userId);
                if (role != null) {
                    userInfo.setIconType(role.getIconType());
                    userInfo.setIconUrl(role.getIconUrl());
                    userInfo.setRoleName(role.getRoleName());
                }
            }
            return Result.success(userInfo);
        } catch (Exception e) {
            log.error("delete error :", e);
            return Result.init(500, "service error", e.getMessage());
        }
    }

    @Override
    public Result deleteUser(Long userId) {
        try {
            removeById(userId);
            tUserRoleMapper.deleteById(userId);
            return Result.success(removeById(userId));
        } catch (Exception e) {
            log.error("query error", e);
            return Result.init(500, "service error", e.getMessage());
        }
    }


}
